package com.jf.cloud.unicomdata.service.impl;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.common.utils.MD5Utils;
import com.jf.cloud.api.leaf.dto.SegmentItemDTO;
import com.jf.cloud.api.leaf.feign.SegmentFeignClient;
import com.jf.cloud.common.constant.DistributedIdKey;
import com.jf.cloud.common.database.dto.PageDTO;
import com.jf.cloud.common.database.util.PageUtil;
import com.jf.cloud.common.database.vo.PageVO;
import com.jf.cloud.common.util.DateUtils;
import com.jf.cloud.unicomdata.config.RandomGenerator;
import com.jf.cloud.unicomdata.config.UnicomConfig;
import com.jf.cloud.unicomdata.dto.HourDataDTO;
import com.jf.cloud.unicomdata.mapper.ScenicSpotMapper;
import com.jf.cloud.unicomdata.model.HourData;
import com.jf.cloud.unicomdata.mapper.HourDataMapper;
import com.jf.cloud.unicomdata.service.HourDataService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 联通小时数据
 *
 * @author zz
 * @date 2023-04-24 17:46:00
 */
@Service
public class HourDataServiceImpl implements HourDataService {

    private static final Logger LOG = LoggerFactory.getLogger(HourDataServiceImpl.class);
    @Autowired
    private HourDataMapper hourDataMapper;

    @Autowired
    private ScenicSpotMapper scenicSpotMapper;

    @Autowired
    private SegmentFeignClient segmentFeignClient;

    @Autowired
    private UnicomConfig unicomConfig;

    @Override
    public PageVO<HourData> page(PageDTO pageDTO, HourDataDTO hourDataDTO) {
        return PageUtil.doPage(pageDTO, () -> hourDataMapper.listByCode(hourDataDTO));
    }

    @Override
    public HourData getByDataId(Long dataId) {
        return hourDataMapper.getByDataId(dataId);
    }

    @Override
    public void save(HourData hourData) {
        hourDataMapper.save(hourData);
    }

    @Override
    public void update(HourData hourData) {
        hourDataMapper.update(hourData);
    }

    @Override
    public void deleteById(Long dataId) {
        hourDataMapper.deleteById(dataId);
    }

    @Override
    public void getUnicomData() {
        String reqUrl="https://travel-api.cubigdata.cn:30000/";
        String seqNo= generateRandomString(8);//随机8位数字字母组合
        String orgCode=unicomConfig.getOrgCode();//机构代码
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHHmmss");
        String curTime= sdf.format(new Date());
        String secret="";
        //md5({orgCode}_{orgSecret}_{curTime}_{sequence}).toUpperCase()
        String sign= MD5Utils.md5Hex((unicomConfig.getOrgCode()+"_"+unicomConfig.getSecret()+"_"+curTime+"_"+seqNo),"UTF-8").toUpperCase();
        JSONObject  reqBody = new JSONObject();
        //根据API的要求，定义相对应的Content-Type
        reqBody.put("sequence", seqNo);
        reqBody.put("orgCode", orgCode);
        reqBody.put("curTime", curTime);
        reqBody.put("sign", sign);
        reqBody.put("area",unicomConfig.getArea());
        reqBody.put("type", "hour");
        SimpleDateFormat sdf1=new SimpleDateFormat("yyyyMMddHH");
        long time=new Date().getTime()-2*60*60*1000;
        reqBody.put("period", sdf1.format(time));
        LOG.info("请求URL："+unicomConfig.getUrl());
        LOG.info("请求参数："+reqBody.toJSONString());
        HttpRequest request = HttpUtil.createPost(unicomConfig.getUrl()).contentType("application/json;charset=utf-8").body(reqBody.toJSONString());
        HttpResponse response = request.execute();
        if(!Objects.isNull(response.body())){
            JSONObject jsonObject= JSONObject.parseObject(response.body());
            LOG.info("请求结果：\n"+jsonObject.toJSONString());
            if(jsonObject.getInteger("code") == 200){
                for (int i = 0; i < jsonObject.getJSONArray("data").size(); i++) {
                    JSONObject datajson=jsonObject.getJSONArray("data").getJSONObject(i);
                    HourData hourData=new HourData();
                    // 获取分布式id
                    SegmentItemDTO segmentItemDTO=new SegmentItemDTO(DistributedIdKey.MALL4CLOUD_UNICOM_DATA, 1);
                    hourData.setDataId(segmentFeignClient.getSegmentId(segmentItemDTO.getKey()).getData());
                    hourData.setCode(datajson.getString("poiId"));
                    hourData.setScenicName(scenicSpotMapper.getNameByCode(datajson.getString("poiId")).getName());
                    hourData.setCreateTime(new Date());
                    hourData.setDataTime(Long.valueOf(sdf1.format(time)));
                    hourData.setTouristNum(datajson.getInteger("touristCnt"));
                    hourData.setTotalNum(datajson.getInteger("nums"));
                    hourDataMapper.save(hourData);
                }

            }
        }else{
            LOG.error("联通接口请求异常");
        }
        LOG.info("联通接口请求结束");
    }


    private static String generateRandomString(int length) {
        String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        Random rng = new Random();
        char[] text = new char[length];
        for (int i = 0; i < length; i++) {
            text[i] = characters.charAt(rng.nextInt(characters.length()));
        }
        return new String(text);
    }

}
